package service

import (
	"context"
	"errors"
	"intelli-dl-online-logo-go/model"
	"intelli-dl-online-logo-go/repository"
	"intelli-dl-online-logo-go/utils"

	"go.mongodb.org/mongo-driver/bson/primitive"
)

type UserService interface {
	CreateUser(req model.UserRequest) (*model.UserResponse, error)
	GetUser(id string) (*model.UserResponse, error)
	UpdateUser(id string, req model.UserRequest) (*model.UserResponse, error)
	DeleteUser(id string) error
	VerifyUser(username, password string) (*model.UserResponse, error)
}

type userService struct {
	userRepo repository.UserRepository
}

func NewUserService() UserService {
	return &userService{
		userRepo: repository.NewUserRepository(),
	}
}

func (us *userService) CreateUser(req model.UserRequest) (*model.UserResponse, error) {
	// 业务逻辑处理
	user := &model.User{
		Username: req.Username,
		Password: req.Password,
		Email:    req.Email,
	}

	createdUser, err := us.userRepo.Create(context.Background(), user)
	if err != nil {
		return nil, err
	}

	return &model.UserResponse{
		ID:       createdUser.ID.Hex(),
		Username: createdUser.Username,
		Email:    createdUser.Email,
	}, nil
}

func (us *userService) GetUser(id string) (*model.UserResponse, error) {
	objID, err := primitive.ObjectIDFromHex(id)
	if err != nil {
		return nil, err
	}

	user, err := us.userRepo.GetByID(context.Background(), objID)
	if err != nil {
		return nil, err
	}

	return &model.UserResponse{
		ID:       user.ID.Hex(),
		Username: user.Username,
		Email:    user.Email,
	}, nil
}

func (us *userService) UpdateUser(id string, req model.UserRequest) (*model.UserResponse, error) {
	objID, err := primitive.ObjectIDFromHex(id)
	if err != nil {
		return nil, err
	}

	user := &model.User{
		Username: req.Username,
		Password: req.Password,
		Email:    req.Email,
	}

	updatedUser, err := us.userRepo.Update(context.Background(), objID, user)
	if err != nil {
		return nil, err
	}

	return &model.UserResponse{
		ID:       updatedUser.ID.Hex(),
		Username: updatedUser.Username,
		Email:    updatedUser.Email,
	}, nil
}

func (us *userService) DeleteUser(id string) error {
	objID, err := primitive.ObjectIDFromHex(id)
	if err != nil {
		return err
	}

	return us.userRepo.Delete(context.Background(), objID)
}

// VerifyUser 验证用户名和密码
func (us *userService) VerifyUser(username, password string) (*model.UserResponse, error) {
	// 根据用户名查找用户
	user, err := us.userRepo.FindByUsername(context.Background(), username)
	if err != nil {
		return nil, err
	}

	// 验证密码
	if user.Password != password {
		return nil, errors.New(utils.ErrLoginFailed)
	}

	return &model.UserResponse{
		ID:       user.ID.Hex(),
		Username: user.Username,
		Email:    user.Email,
	}, nil
}
